<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="昵称">
              <a-input placeholder="请输入昵称" v-model="queryParam.nickname"></a-input>
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="手机号">
              <a-input placeholder="请输入手机号" v-model="queryParam.phone"></a-input>
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="用户身份">
              <j-dict-select-tag v-model="queryParam.level"
                                 dictCode="hms_hand_config,name,level,id IS NOT NULL ORDER BY level ASC"
                                 placeholder="全部"/>
            </a-form-item>
          </a-col>


          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="性别">
              <j-dict-select-tag v-model="queryParam.sex"
                                 dictCode="sex"
                                 placeholder="全部"/>
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="年龄">
              <a-input-number placeholder="全部" :min="0" :step="1" :precision="0" style="width:100%"
                              v-model="queryParam.age"></a-input-number>
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="省份">
              <a-select v-model="queryParam.pid" @change="getCList" :allowClear="true" placeholder="全部">
                <a-select-option v-for="(item3,index3) in pList" :key="index3" :value="item3.id">
                  {{ item3.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="城市">
              <a-select v-model="queryParam.cid" :allowClear="true" placeholder="全部">
                <a-select-option v-for="(item3,index3) in cList" :key="index3" :value="item3.id">
                  {{ item3.name }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="终端">
              <j-dict-select-tag v-model="queryParam.deviceType"
                                 dictCode="device_type"
                                 placeholder="全部"/>
            </a-form-item>
          </a-col>

          <a-col :xl="10" :lg="7" :md="8" :sm="24">
            <a-form-item label="注册时间">
              <a-range-picker v-model="date1" format="YYYY-MM-DD" :placeholder="['开始时间', '结束时间']"
                              @change="onDateChange"/>
            </a-form-item>
          </a-col>
          <a-col :xl="10" :lg="7" :md="8" :sm="24">
            <a-form-item label="最近登录时间">
              <a-range-picker v-model="date2" format="YYYY-MM-DD" :placeholder="['开始时间', '结束时间']"
                              @change="onDateLoginChange"/>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <div>
      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        class="j-table-force-wrap"
        @change="handleTableChange">

        <template slot="statusSlot" slot-scope="text,record,index">
          <a-switch v-model="dataSource[index].status===1"
                    checked-children="正常" un-checked-children="冻结"
                    @click="handleChange(index)"
          ></a-switch>
        </template>

        <template slot="userSlot" slot-scope="text,record">
          <div style="display:flex;align-items: center;">
            <a-avatar :src="record.headUrl" :size="50" icon="user"/>
            <div style="padding-left:10px;">
              <div>
                <a-icon type="user"></a-icon>
                {{ record.nickname }}
              </div>
              <div>
                <a-icon type="phone"></a-icon>
                {{ record.phone }}
              </div>
              <div>
                <a-icon type="calendar"/>
                注册时间：
              </div>
              <div>{{ record.createTime }}</div>
            </div>
          </div>
        </template>
        <template slot="repSlot" slot-scope="text,record">
          <div>积分：{{ record.integral }}</div>
          <div>余额：{{ record.balance }}</div>
          <div>订单数量：{{ record.orderNum }}</div>
          <div>支付金额：{{ record.orderAmount }}</div>
        </template>

        <template slot="propSlot" slot-scope="text,record">
          <div>身份：{{ record.levelName ? record.levelName : '普通用户' }}</div>
          <div>性别：{{ record.sex_dictText }}</div>
          <div>生日：{{ record.dateBirth ? record.dateBirth : '未知' }}</div>
          <div>地区：{{ record.full_address }}</div>
          <div>
            终端：
            <a-tag color="#f50" v-if="record.deviceType == 0">
              未知
            </a-tag>
            <a-tag color="#2db7f5" v-if="record.deviceType == 1">
              Android
            </a-tag>
            <a-tag color="#87d068" v-if="record.deviceType == 2">
              IOS
            </a-tag>
          </div>
        </template>

        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" height="55px" alt=""
               style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <!--标签和分组信息展示-->
        <template slot="crmTags" slot-scope="text,record">
          <div v-for="(item,index) in record.crmTags" :key="index" style="margin-bottom:2px;">
            <a-tag :color="item.type==1?'#87d068':'#108ee9'">
              {{ item.name }}
            </a-tag>
          </div>
        </template>

        <template slot="crmGroups" slot-scope="text,record">
          <div v-for="(item,index) in record.crmGroups" :key="index" style="margin-bottom:2px;">
            <a-tag>
              {{ item.name }}
            </a-tag>
          </div>
        </template>

        <span slot="action" slot-scope="text,record,index">
          <a @click="goInfo(record)">查看详情</a>
           <a-divider type="vertical"/>
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down"/></a>
            <a-menu slot="overlay">
              <a-menu-item>
              <a @click="labelEdit(record)">标签编辑</a>
              </a-menu-item>
              <a-menu-item>
               <a @click="levelEdit(record)" v-if="record.isHand==0">设为分销员</a>
                 <a @click="levelEdit(record)" v-else>调整分销员等级</a>
              </a-menu-item>
              <a-menu-item>
                <a @click="addIntegral(record.id,index)">增加积分</a>
              </a-menu-item>
               <a-menu-item>
                <a @click="subIntegral(record,index)">减少积分</a>
              </a-menu-item>
               <a-menu-item v-if="record.isMember==1">
                  <a-popconfirm title="确定从企业中移除吗?" @confirm="() => removeCompany(record.id)">
                        <a>从企业中移除</a>
                 </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
          <!--          <br/>
                    <a @click="labelEdit(record)">标签编辑</a>
                    <br/>
                    <a @click="levelEdit(record)" v-if="record.isHand==0">设为分销员</a>
                    <a @click="levelEdit(record)" v-if="record.isHand==1">调整分销员等级</a>
                    <br/>-->
          <!--          <a-popconfirm v-if="record.status==1" title="确定冻结吗?" @confirm="() => changerState(record)">
                      <a>冻结</a>
                    </a-popconfirm>
                    <a-popconfirm v-else title="确定解冻吗?" @confirm="() => changerState(record)">
                      <a>解冻</a>
                    </a-popconfirm>-->
          <!--          <br/>
                    <a-popconfirm v-if="record.isMember==1" title="确定从企业中移除吗?" @confirm="() => removeCompany(record.id)">
                      <a>从企业中移除</a>
                    </a-popconfirm>-->
        </span>
      </a-table>
    </div>

    <a-modal :title="integralTitle" :visible="integral_visible" :confirm-loading="integral_confirmLoading"
             @ok="integralOk"
             @cancel="integral_visible=false">
      <p>
        积分数量 :
        <a-input-number :precision="0"
                        :step="1"
                        :max="max_integral"
                        placeholder="积分数量"
                        v-model="integral"
                        style="width: 60%;margin-left: 3%;"></a-input-number>
      </p>
    </a-modal>
    <crm-tag-ref ref="modalLabels" :selectionType="'checkbox'" @ok="modalLabelOk"></crm-tag-ref>
    <a-modal title="设置分销员" :visible="set_hand_visible" :confirm-loading="set_hand_confirmLoading" @ok="levelEditOk"
             @cancel="handleCancel">
      <p>
        身份：
        <a-select size="small" style="margin:0 5px;" v-model="set_hand_level">
          <a-select-option v-for="(item3,index3) in levelList" :key="index3" :value="item3.level">
            {{ item3.name }}
          </a-select-option>
        </a-select>
      </p>
    </a-modal>
  </a-card>
</template>


<script>

import '@/assets/less/TableExpand.less'
import {mixinDevice} from '@/utils/mixin'
import {JeecgListMixin} from '@/mixins/MyJeecgListMixin'
import JDate from '@/components/jeecg/JDate.vue'
import JDictSelectTag from '@/components/dict/JDictSelectTag'
import {BoneCommonMixin} from "@/mixins/BoneCommonMixin";
import CrmTagRef from '@/views/gospel/crm/modules/CrmTagRef'
import {putAction, getAction, postAction} from '@/api/manage'

export default {
  name: 'TipMemberList',
  mixins: [JeecgListMixin, mixinDevice, BoneCommonMixin],
  components: {
    JDate, JDictSelectTag, CrmTagRef
  },
  data() {
    return {
      set_hand_visible: false,
      set_hand_confirmLoading: false,
      set_hand_level: 1,
      select_id: null,
      max_integral: 0,
      integral_confirmLoading: false,
      integral_visible: false,
      integral_url: '',
      integralTitle: '加积分',
      uid: null,
      integral: 0,
      groupId: "",
      visible: false,
      isShow: false,
      description: 'tip_member管理页面',
      // 表头
      columns: [
        {
          title: '序号',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '用户',
          align: "left",
          dataIndex: 'id',
          scopedSlots: {customRender: "userSlot"}
        },
        {
          title: '统计',
          align: "left",
          dataIndex: 'score',
          scopedSlots: {customRender: "repSlot"}
        },
        {
          title: '用户属性',
          align: "left",
          dataIndex: 'role',
          scopedSlots: {customRender: "propSlot"}
        },

        {
          title: '用户标签',
          align: "left",
          scopedSlots: {customRender: 'crmTags'}
        },
        {
          title: '用户分组',
          align: "left",
          scopedSlots: {customRender: 'crmGroups'}
        },
        // {
        //   title: '终端类型',
        //   align: "center",
        //   dataIndex: 'deviceType_dictText'
        // },
        // {
        //     title: '是否是游客',
        //     align: "center",
        //     dataIndex: 'isVisitor_dictText'
        // },
        {
          title: '用户状态',
          align: "center",
          dataIndex: 'status',
          scopedSlots: {customRender: "statusSlot"}
        },
        {
          title: '登录时间',
          align: "center",
          dataIndex: 'loginTime',
          width: 100,
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          fixed: "right",
          width: 147,
          scopedSlots: {customRender: 'action'}
        }
      ],
      url: {
        list: "/tipMember/list",
        edit: "/tipMember/edit",
        userstatus: "/tipMember/userstatus",
        setHand: "/tipMember/setHand",
        editLabels: "/tipMember/editLabels",
        delete: "/tipMember/delete",
        deleteBatch: "/tipMember/deleteBatch",
        exportXlsUrl: "/tipMember/exportXls",
        importExcelUrl: "tipMember/importExcel",
        addressList: "/common/district-api/index",
        changeStatus: "/admin/ums/changeStatus",
      },
      dictOptions: {},
      usererstatus: 0,
      levelList: [],
      pList: [],
      cList: [],
      date1: undefined,
      date2: undefined,
      changeIntegral: {
        index: null, //修改的索引值
        flag: null, // 1增加 //0减少
      },
    }
  },
  created() {
    if (this.$route.query.id != null) {
      this.queryParam.groupId = this.$route.query.id
    }
    this.loadData()
    this.getLevels()
    this.getPList()


  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    handleChange(index) {
      this.dataSource[index].status === 0 ? this.dataSource[index].status = 1 : this.dataSource[index].status = 0;
      putAction(this.url.changeStatus + "/" + this.dataSource[index].id + "/" + this.dataSource[index].status).then(res => {
        if (res.code === 200) {
          this.$message.success(res.message);
        } else {
          this.$message.error(res.message);
          this.dataSource[index].status === 0 ? this.dataSource[index].status = 1 : this.dataSource[index].status = 0;
        }
      });
    },
    searchReset() {
      if (this.queryParam.groupId) {
        this.queryParam = {
          groupId: this.queryParam.groupId
        }
      } else {
        this.queryParam = {}
      }
      this.date1 = undefined
      this.date2 = undefined
      this.loadData(1)
    },
    onDateLoginChange: function (value, dateString) {
      this.queryParam.loginTime_begin = dateString[0]
      this.queryParam.loginTime_end = dateString[1]
    },
    levelEdit(record) {
      this.select_id = record.id
      this.set_hand_visible = true
      if (record.level) {
        this.set_hand_level = record.level
      }
    },
    levelEditOk() {
      this.set_hand_confirmLoading = true
      putAction(this.url.setHand, {id: this.select_id, level: this.set_hand_level}).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.getAllMemberList()
        }
        this.loading = false
        this.handleCancel()
      })
    },
    handleCancel() {
      this.set_hand_visible = false
      this.set_hand_confirmLoading = false
      this.set_hand_level = 1
    },
    labelEdit(record) {
      let self = this
      self.select_id = record.id
      self.$refs.modalLabels.visible = true
      self.$refs.modalLabels.checkedKeys = []
      self.$refs.modalLabels.checkedRows = []
      if (record.crmTags) {
        for (let i = 0; i < record.crmTags.length; i++) {
          self.$refs.modalLabels.checkedRows.push({id: record.crmTags[i].id})
          self.$refs.modalLabels.checkedKeys.push(record.crmTags[i].id)
        }
      }

      self.$refs.modalLabels.open()
    },
    modalLabelOk(rows, keys) {
      var that = this
      if (that.select_id) {
        putAction(that.url.editLabels, {id: that.select_id, tagList: rows}).then((res) => {
          if (res.success) {
            that.$message.success(res.message)
            that.getAllMemberList()
            that.onClearSelected()
          } else {
            that.$message.warning(res.message)
          }
        }).finally(() => {
          that.loading = false
        })
      }

    },

    getLevels() {
      var that = this
      getAction("/mallPlus/hmsHandConfig/list", {}).then((res) => {
        if (res.success) {
          that.levelList = res.result.records
        }
      })
    },

    getPList() {
      var that = this
      getAction("/common/district-api/index", {upid: 0}).then((res) => {
        if (res.success) {
          that.pList = res.result
        }
      })
    },

    getCList() {
      var that = this
      getAction("/common/district-api/index", {upid: this.queryParam.pid}).then((res) => {
        if (res.success) {
          that.cList = res.result
        }
      })
    },


    initDictConfig() {
    },
    goInfo(record) {
      this.$router.push({path: '/member/member/memberinfo', query: {id: record.id}})
    },
    showModal() {
      this.visible = true
    },
    hideModal() {
      this.visible = false
    },
    confirm() {
      this.$confirm({
        title: 'Confirm',
        content: 'Bla bla ...',
        okText: '确认',
        cancelText: '取消',
      })
    },
    changerState(record) {
      let userstatus = 1
      if (record.status == 0) {
        userstatus = 1
      } else if (record.status == 1) {
        userstatus = 0
      }
      putAction(this.url.userstatus, {id: record.id, status: userstatus}).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.getAllMemberList()
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    getAllMemberList() {
      console.log("conming")
      var params = this.getQueryParams()//查询条件
      getAction(this.url.list, params).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    getListByGid() {
      getAction(this.url.list, this.groupId).then((res) => {
        if (res.success) {
          this.dataSource = res.result.records
          this.ipagination.total = res.result.total
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    removeCompany(id) {
      putAction(this.url.edit, {id: record.id, isMember: 0}).then((res) => {
        if (res.success) {
          this.$message.success(res.message)
          this.getAllMemberList()
        }
        if (res.code === 510) {
          this.$message.warning(res.message)
        }
        this.loading = false
      })
    },
    addIntegral(id, index) {
      this.uid = id
      this.max_integral = 100000000
      this.integralTitle = "增加积分"
      this.integral_url = "/tipMember/addIntegral"
      this.integral = 0;
      this.integral_visible = true;
      this.changeIntegral.index = index;
      this.changeIntegral.flag = 1;
    },
    subIntegral(record, index) {
      this.uid = record.id
      this.max_integral = record.integral
      this.integralTitle = "减少积分"
      this.integral_url = "/tipMember/subIntegral"
      this.integral = 0
      this.integral_visible = true;
      this.changeIntegral.index = index;
      this.changeIntegral.flag = 0;
    },
    integralOk() {
      if (!this.integral) {
        this.$message.warning("输入积分必须大于0")
        return
      }
      this.integral_confirmLoading = true;
      let index = this.changeIntegral.index;
      if (index == null || this.changeIntegral.flag == null) {
        this.showWarn("数据异常");
        return;
      }
      let message = this.changeIntegral.flag === 1 ? "增加积分" : "减少积分";
      putAction(this.integral_url, {id: this.uid, integral: this.integral}).then((res) => {
        if (res.success) {
          this.showSuccess(message + res.message);
          // this.getAllMemberList()
          // 直接修改索引对应数据的记录
          if (this.changeIntegral.flag === 1) {
            this.dataSource[index].integral += this.integral;
          } else {
            this.dataSource[index].integral -= this.integral;
          }
          this.integral_visible = false;
        } else {
          this.showError(message + res.message);
        }
      }).finally(() => {
        this.integral_confirmLoading = false
      })
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
